import React, {useCallback, useEffect, useState} from 'react';
import {
  View,
  Text,
  FlatList,
  Image,
  StyleSheet,
  RefreshControl,
  TouchableOpacity,
} from 'react-native';
import {useFocusEffect} from '@react-navigation/native';
import theme from '../utils/theme';
import {normalize, screenHeight, stringTofixed} from '../utils/commonUtils';
import API from '../Network/Api';
import {CustomText} from '../customview/CustomText';
import {useIsFocused} from '@react-navigation/native';

const ServiceChargePage = ({navigation}) => {
  const [records, setRecords] = useState([]);
  const [refreshing, setRefreshing] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(false);
  const [totalEarnings, setTotalEarnings] = useState(0);
  const isFocused = useIsFocused();

  useFocusEffect(
    useCallback(() => {
      const parentNavigator = navigation.getParent();
      if (parentNavigator) {
        parentNavigator.setOptions({tabBarStyle: {display: 'none'}});
      }
    }, [navigation]),
  );

  useEffect(() => {
    if (isFocused) {
      fetchRecords(1);
    }
  }, [isFocused]);

  const fetchRecords = async currentPage => {
    try {
      const response = await API.getChargeRecordList(currentPage, 20);
      if (response.resultCode === '1') {
        const list = response.data.chargeRecord.rows || [];
        const total = response.data.chargeRecord.total;
        if (currentPage === 1) {
          setRecords(list);
          if (list.length > 0) {
            const firstItem = list[0];
            setTotalEarnings(stringTofixed(firstItem.zzfwf));
          }
        } else {
          setRecords(prevRecords => [...prevRecords, ...list]);
        }
        setHasMore(records.length + list.length < total);
      }
    } catch (error) {
      console.error('获取收益记录失败:', error);
    } finally {
      setRefreshing(false);
    }
  };

  const onRefresh = async () => {
    setRefreshing(true);
    setPage(1);
    await fetchRecords(1);
  };

  const onEndReached = async () => {
    if (hasMore) {
      const nextPage = page + 1;
      setPage(nextPage);
      await fetchRecords(nextPage);
    }
  };

  const maskText = type => {
    if (type === '1') {
      return '充值 - 服务费';
    } else if (type === '2') {
      return '转拍 - 服务费';
    } else if (type === '3') {
      return '转入 - 服务费';
    } else if (type === '4') {
      return '转出 - 服务费';
    } else {
      return '服务费发生变动';
    }
  };

  const renderItem = ({item}) => (
    <View style={styles.recordItem}>
      <Image source={theme.app.logo} style={styles.itemImage} />
      <View style={styles.itemInfo}>
        <CustomText style={styles.itemDescription}>
          {maskText(item.fwfbhlx)}
        </CustomText>
        <CustomText style={styles.itemTime}>{item.createTime}</CustomText>
      </View>
      {item.fwfbhlx === '1' || item.fwfbhlx === '3' ? (
        <CustomText style={styles.itemAmount}>
          +{stringTofixed(item.bhfwf)}
        </CustomText>
      ) : (
        <CustomText style={styles.item1Amount}>
          -{stringTofixed(item.bhfwf)}
        </CustomText>
      )}
    </View>
  );

  const EmptyListComponent = () => (
    <View style={styles.emptyListContainer}>
      <CustomText style={styles.emptyListText}>暂无服务费明细</CustomText>
    </View>
  );

  const transferHandlePress = () => {
    navigation.navigate('ServiceFeeTransferPage', {
      totalEarnings: totalEarnings,
    });
  };

  return (
    <View style={styles.container}>
      {/* 显示总收益 */}
      <View style={styles.totalEarningsContainer}>
        <View>
          <CustomText style={styles.totalEarningsTipText}>
            可用服务费（元）
          </CustomText>
          <CustomText style={styles.totalEarningsText}>
            {totalEarnings}
          </CustomText>
        </View>
        <TouchableOpacity
          style={styles.zhuanzhangView}
          onPress={transferHandlePress}>
          <CustomText style={styles.zhuanzhangText}>转账</CustomText>
        </TouchableOpacity>
      </View>
      {/* 收益记录列表 */}
      <FlatList
        data={records}
        renderItem={renderItem}
        keyExtractor={item => item.id}
        style={styles.recordList}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
        onEndReached={onEndReached}
        onEndReachedThreshold={0.1}
        ListEmptyComponent={EmptyListComponent}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  totalEarningsContainer: {
    backgroundColor: theme.colors.primary,
    marginTop: 10,
    marginHorizontal: 10,
    borderRadius: 10,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  zhuanzhangView: {
    alignSelf: 'center',
    marginRight: 20,
    borderRadius: 15,
    height: 30,
    backgroundColor: '#fff',
    justifyContent: 'center',
  },
  zhuanzhangText: {
    color: theme.colors.primary,
    fontSize: normalize(14),
    marginVertical: 5,
    marginHorizontal: 15,
  },
  totalEarningsTipText: {
    fontSize: normalize(16),
    color: '#fff',
    marginTop: 20,
    marginLeft: 15,
  },
  totalEarningsText: {
    fontSize: normalize(24),
    color: '#fff',
    marginTop: 20,
    marginBottom: 20,
    marginLeft: 15,
  },
  recordList: {
    padding: 10,
  },
  recordItem: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#fff',
    padding: 10,
    marginBottom: 10,
    borderRadius: 8,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 2,
  },
  itemImage: {
    width: 40,
    height: 40,
    borderRadius: 20,
    marginRight: 15,
  },
  itemInfo: {
    flex: 1,
  },
  itemDescription: {
    fontSize: normalize(14),
    fontWeight: '500',
    color: '#333',
  },
  itemTime: {
    fontSize: normalize(12),
    color: '#999',
    marginTop: 5,
  },
  itemAmount: {
    fontSize: normalize(15),
    color: '#FF6B6B',
  },
  item1Amount: {
    fontSize: normalize(15),
    color: '#000',
  },
  emptyListContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: screenHeight / 3,
  },
  emptyListText: {
    flex: 1,
    fontSize: normalize(16),
    color: '#999',
  },
});

export default ServiceChargePage;
